package com.lqian.share;

import java.util.concurrent.atomic.AtomicInteger;

/*
 * @description: 原子性自增与加锁方式对比
 * @author: Melody_LQ
 * @date: 2022/11/16 8:36 PM
 **/
public class CAS_Lock_Performance_03 {
    private int value;

    public CAS_Lock_Performance_03(int value){
        this.value = value;
    }
    public synchronized int increase(){
        return value++;
    }
    public int getValue(){
        return value;
    }

    public static void main(String args[]){
        long start = System.currentTimeMillis();
        CAS_Lock_Performance_03 test = new CAS_Lock_Performance_03(0);
        for( int i=0;i< 100000000;i++){
            test.increase();
        }
        long end = System.currentTimeMillis();
        System.out.println(test.getValue()+" times increase synchronize time cost:"+(end -start)+" ms");

        start = System.currentTimeMillis();
        AtomicInteger atomic = new AtomicInteger(0);
        for(int i=0;i< 100000000;i++){
            atomic.incrementAndGet();
        }
        end = System.currentTimeMillis();
        System.out.println(atomic.intValue() +" times increase atomic time cost:"+(end - start)+" ms" );
    }

}
